<script setup lang="ts">
import { reactive, ref } from 'vue';

import { Page } from '@vben/common-ui';

import {
  Breadcrumb,
  BreadcrumbItem,
  Button,
  DatePicker,
  Table,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { ChevronDown, ChevronRight, Download, Printer } from 'lucide-vue-next';

interface ProfitStatementRecord {
  currentMonthAmount: null | number;
  currentYearAmount: null | number;
  isCollapsible?: boolean;
  isDetailRow?: boolean;
  isExpanded?: boolean;
  isGroupRow?: boolean;
  item: string;
  key: string;
  level?: number;
  lineNumber: string;
  parentKey?: string;
}

interface QueryForm {
  accountingPeriod: dayjs.Dayjs | null;
}

// 查询表单数据
const queryForm = reactive<QueryForm>({
  accountingPeriod: dayjs('2025-01'),
});

// 表格列配置
const columns = [
  {
    title: '项目',
    dataIndex: 'item',
    key: 'item',
    width: 300,
    align: 'left' as const,
  },
  {
    title: '行次',
    dataIndex: 'lineNumber',
    key: 'lineNumber',
    width: 80,
    align: 'center' as const,
  },
  {
    title: '本月金额',
    dataIndex: 'currentMonthAmount',
    key: 'currentMonthAmount',
    width: 150,
    align: 'right' as const,
  },
  {
    title: '本年累计金额',
    dataIndex: 'currentYearAmount',
    key: 'currentYearAmount',
    width: 150,
    align: 'right' as const,
  },
];

// 利润表原始数据（包含所有项目）
const originalProfitData = ref<ProfitStatementRecord[]>([
  // 一、营业收入
  {
    key: '1',
    item: '一、营业收入',
    lineNumber: '1',
    currentMonthAmount: 5_000_000,
    currentYearAmount: 50_000_000,
    isGroupRow: true,
    level: 0,
  },
  // 减：营业成本
  {
    key: '2',
    item: '减：营业成本',
    lineNumber: '2',
    currentMonthAmount: 3_000_000,
    currentYearAmount: 30_000_000,
    isGroupRow: true,
    level: 0,
  },
  // 税金及附加（可折叠）
  {
    key: '3',
    item: '税金及附加',
    lineNumber: '3',
    currentMonthAmount: 150_000,
    currentYearAmount: 1_500_000,
    isCollapsible: true,
    isExpanded: false,
    level: 0,
  },
  {
    key: '3-1',
    item: '营业税金及附加',
    lineNumber: '11',
    currentMonthAmount: 80_000,
    currentYearAmount: 800_000,
    isDetailRow: true,
    level: 1,
    parentKey: '3',
  },
  {
    key: '3-2',
    item: '管理费用',
    lineNumber: '14',
    currentMonthAmount: 70_000,
    currentYearAmount: 700_000,
    isDetailRow: true,
    level: 1,
    parentKey: '3',
  },
  // 销售费用（可折叠）
  {
    key: '4',
    item: '销售费用',
    lineNumber: '18',
    currentMonthAmount: 200_000,
    currentYearAmount: 2_000_000,
    isCollapsible: true,
    isExpanded: false,
    level: 0,
  },
  {
    key: '4-1',
    item: '投资收益（损失以"-"号填列）',
    lineNumber: '20',
    currentMonthAmount: 50_000,
    currentYearAmount: 500_000,
    isDetailRow: true,
    level: 1,
    parentKey: '4',
  },
  {
    key: '4-2',
    item: '其他收益',
    lineNumber: '21',
    currentMonthAmount: 150_000,
    currentYearAmount: 1_500_000,
    isDetailRow: true,
    level: 1,
    parentKey: '4',
  },
  // 加：其他收益
  {
    key: '5',
    item: '加：其他收益',
    lineNumber: '22',
    currentMonthAmount: 100_000,
    currentYearAmount: 1_000_000,
    level: 0,
  },
  {
    key: '6',
    item: '减：营业外支出',
    lineNumber: '24',
    currentMonthAmount: 50_000,
    currentYearAmount: 500_000,
    level: 0,
  },
  // 二、营业利润（亏损以"-"号填列）
  {
    key: '7',
    item: '二、营业利润（亏损以"-"号填列）',
    lineNumber: '21',
    currentMonthAmount: 1_700_000,
    currentYearAmount: 17_000_000,
    isGroupRow: true,
    level: 0,
  },
  // 三、利润总额（亏损总额以"-"号填列）
  {
    key: '8',
    item: '三、利润总额（亏损总额以"-"号填列）',
    lineNumber: '30',
    currentMonthAmount: 1_650_000,
    currentYearAmount: 16_500_000,
    isGroupRow: true,
    level: 0,
  },
]);

// 显示的表格数据（根据折叠状态过滤）
const profitStatementData = ref<ProfitStatementRecord[]>([]);

// 初始化显示数据
const initializeDisplayData = () => {
  profitStatementData.value = originalProfitData.value.filter((item) => {
    if (item.level === 0) return true;
    if (item.parentKey) {
      const parent = originalProfitData.value.find(
        (p) => p.key === item.parentKey,
      );
      return parent?.isExpanded === true;
    }
    return false;
  });
};

// 切换折叠状态
const toggleExpand = (record: ProfitStatementRecord) => {
  if (!record.isCollapsible) return;

  const item = originalProfitData.value.find((item) => item.key === record.key);
  if (item) {
    item.isExpanded = !item.isExpanded;
    initializeDisplayData();
  }
};

// 格式化金额
const formatAmount = (amount: null | number): string => {
  if (amount === null || amount === 0) return '';
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
};

// 事件处理函数
const handleBackToWorkspace = () => {
  // 返回工作台
};

const handlePrint = () => {
  // 打印利润表
};

const handleDownload = () => {
  // 下载利润表
};

// 初始化数据
initializeDisplayData();
</script>

<template>
  <Page description="利润表页面，显示企业在特定期间的经营成果" title="利润表">
    <!-- 页面顶部栏 -->
    <div class="mb-4 flex items-center justify-between">
      <!-- 左侧公司名称 -->
      <div class="text-lg font-medium text-gray-800">
        北京神州源科技有限公司
      </div>

      <!-- 中间面包屑 -->
      <div class="flex-1 px-4">
        <Breadcrumb>
          <BreadcrumbItem>报表中心</BreadcrumbItem>
          <BreadcrumbItem>利润表</BreadcrumbItem>
        </Breadcrumb>
      </div>

      <!-- 右侧操作区 -->
      <div class="flex items-center space-x-2">
        <Button type="primary" @click="handleBackToWorkspace">
          返回工作台
        </Button>
      </div>
    </div>

    <!-- 利润表核心功能区 -->
    <div class="rounded-lg bg-white p-6 shadow-sm">
      <!-- 编制信息与筛选区 -->
      <div class="mb-6 space-y-4">
        <!-- 编制单位和账期选择 -->
        <div class="flex items-center space-x-8">
          <!-- 编制单位 -->
          <div class="flex items-center space-x-4">
            <span class="text-sm font-medium text-gray-700">编制单位：</span>
            <span class="text-sm text-gray-900">北京神州源科技有限公司</span>
          </div>

          <!-- 账期选择 -->
          <div class="flex items-center space-x-4">
            <span class="text-sm font-medium text-gray-700">账期：</span>
            <DatePicker
              v-model:value="queryForm.accountingPeriod"
              picker="month"
              placeholder="选择账期"
              class="w-40"
              format="YYYY-MM"
            />
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex items-center justify-end space-x-2">
          <Button type="primary" @click="handlePrint">
            <Printer class="mr-1 h-4 w-4" />
            打印
          </Button>
          <Button type="primary" @click="handleDownload">
            <Download class="mr-1 h-4 w-4" />
            下载
          </Button>
        </div>
      </div>

      <!-- 利润表表格 -->
      <div class="overflow-x-auto">
        <Table
          :columns="columns"
          :data-source="profitStatementData"
          :pagination="false"
          size="small"
          bordered
          :scroll="{ x: 800 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'item'">
              <div
                :class="{
                  'font-medium text-gray-900': record.isGroupRow,
                  'cursor-pointer': record.isCollapsible,
                }"
                :style="{ paddingLeft: `${(record.level || 0) * 20 + 8}px` }"
                @click="record.isCollapsible ? toggleExpand(record) : undefined"
              >
                <!-- 折叠图标 -->
                <span
                  v-if="record.isCollapsible"
                  class="mr-2 inline-flex h-4 w-4 items-center justify-center"
                >
                  <ChevronRight
                    v-if="!record.isExpanded"
                    class="h-3 w-3 text-gray-500"
                  />
                  <ChevronDown v-else class="h-3 w-3 text-gray-500" />
                </span>
                <span>{{ record.item }}</span>
              </div>
            </template>
            <template v-else-if="column.key === 'lineNumber'">
              <span class="text-center">
                {{ record.lineNumber }}
              </span>
            </template>
            <template v-else-if="column.key === 'currentMonthAmount'">
              <span class="text-right">
                {{ formatAmount(record.currentMonthAmount) }}
              </span>
            </template>
            <template v-else-if="column.key === 'currentYearAmount'">
              <span class="text-right">
                {{ formatAmount(record.currentYearAmount) }}
              </span>
            </template>
          </template>
        </Table>
      </div>
    </div>
  </Page>
</template>
